package com.pospi.xstore.ui.cash_ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.lany.sp.SPHelper;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.xstore.App;
import com.pospi.xstore.R;
import com.pospi.xstore.adapter.RefundAdapter;
import com.pospi.xstore.dao.OrderDao;
import com.pospi.xstore.dto.OrderBeen;
import com.pospi.xstore.dto.OrderDto;
import com.pospi.xstore.greendao.OrderBeenDao;
import com.pospi.xstore.http.UploadData;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.GetData;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class RefundActivity extends BaseActivity {

    @Bind(R.id.et_order)
    EditText etOrder;
    @Bind(R.id.lv_order)
    ListView lvOrder;
    @Bind(R.id.tv_date)
    TextView tv_date;
    @Bind(R.id.iv_search)
    ImageView iv_search;

    private List<OrderBeen> orderDtos = new ArrayList<>();

    private RefundAdapter adapter;
    public static final String REFUNDS = "refunds";
    private OrderBeenDao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_refund);
        setTitle("交易记录");
        ButterKnife.bind(this);
        setMenuImage(R.drawable.icon_up);
        dao = App.getInstance().getDaoSession().getOrderBeenDao();

        adapteData(GetData.getYYMMDDTime());
        tv_date.setText(GetData.getYYMMDDTime());
        tv_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                long mixYears = 1L * 365 * 1000 * 60 * 60 * 24L;
                TimePickerDialog dialogYearMonthDay = new TimePickerDialog.Builder()
                        .setType(Type.YEAR_MONTH_DAY)
                        .setTitleStringId("选择日期")
                        .setWheelItemTextSize(16)
                        .setThemeColor(R.color.title)
                        .setMaxMillseconds(System.currentTimeMillis())
                        .setMinMillseconds(System.currentTimeMillis() - mixYears)
                        .setCallBack(new OnDateSetListener() {
                            @Override
                            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                                Date date = new Date(millseconds);
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                                String time = format.format(date);
                                tv_date.setText(time);
                                searchOrder();
                            }
                        })
                        .build();
                dialogYearMonthDay.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
            }
        });
        iv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search();
            }
        });

        lvOrder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(RefundActivity.this, OrderDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(REFUNDS, orderDtos.get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        searchOrder();
    }

    public void adapteData(String date) {
        adapter = new RefundAdapter(getApplicationContext(), orderDtos);
        lvOrder.setAdapter(adapter);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        searchOrder();
    }

    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);

        showDialog();

        for (OrderBeen been : orderDtos) {
            if (been.getUpStatus().equals(Constant.UP_NO)) {
                UploadData.upOrder(this, been, "");
            }
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(4000);
                    close();
                    searchOrder();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    @Override
    protected void onStart() {
        super.onStart();
        etOrder.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    boolean sd = ((InputMethodManager) etOrder.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    RefundActivity.this.getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    search();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    public void searchOrder() {
        String maxNo;
        try {
            maxNo = etOrder.getText().toString().trim();
            List<OrderBeen> selectDto = dao.queryBuilder().where(OrderBeenDao.Properties.Time.eq(tv_date.getText().toString()),
                    OrderBeenDao.Properties.Shop_id.eq(SPHelper.getInstance().getString(Constant.STORE_ID)),
                    OrderBeenDao.Properties.Cashiername.eq(SPHelper.getInstance().getString(Constant.COUNT_NAME))).list();
            if (selectDto == null) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showToast("未查询到该订单");
                    }
                });

            } else {
                orderDtos.clear();
                orderDtos.addAll(selectDto);
                adapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
        }
    }
    public void search() {
        String maxNo;
        try {
            maxNo = etOrder.getText().toString().trim();
            OrderBeen selectDto = dao.queryBuilder().where(OrderBeenDao.Properties.Time.eq(maxNo),
                    OrderBeenDao.Properties.Shop_id.eq(SPHelper.getInstance().getString(Constant.STORE_ID)),
                    OrderBeenDao.Properties.Cashiername.eq(SPHelper.getInstance().getString(Constant.COUNT_NAME))).unique();
            if (selectDto == null) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showToast("未查询到该订单");
                    }
                });
            } else {
                orderDtos.clear();
                orderDtos.add(selectDto);
                adapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
        }
    }

}